/**
 * 
 */
package sailing.ui.systemsetting.model;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.jdesktop.application.SingleFrameApplication;

import cjlite.utils.Lists;

import sailing.entity.AccountingSubject;
import sailing.entity.BankName;
import sailing.entity.SubjectCategory;
import sailing.managers.AccountingSubjectManager;
import sailing.managers.BankNameManager;
import sailing.ui.model.SailingTableModel;

/**
 * @author kevin
 * 
 */
public class SubjectTableModel extends SailingTableModel {

	private static String[] columnName = { "科目编号", "会计科目名称", "操作" };
	private boolean showEditBtn = false;
	private List<AccountingSubject> asList = Lists.newArrayList();
	private SubjectCategory sc;

	/**
	 * @param sc
	 * @param application
	 */
	public SubjectTableModel(SubjectCategory sc, SingleFrameApplication application) {
		super(application);
		this.sc = sc;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getRowCount()
	 */
	@Override
	public int getRowCount() {
		return asList.size();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getColumnCount()
	 */
	@Override
	public int getColumnCount() {
		return showEditBtn ? columnName.length : columnName.length - 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getValueAt(int, int)
	 */
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		if (rowIndex >= this.asList.size()) {
			return "";
		}

		AccountingSubject bn = this.asList.get(rowIndex);

		switch (columnIndex) {
		case 0:
			return bn.getCode();
		case 1:
			return bn.getName();
		case 2:
			return bn;
		}

		return "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see sailing.ui.model.SailingTableModel#updateModel()
	 */
	@Override
	public void updateModel() {
		AccountingSubjectManager asm = this.getApplication().getContext().getIoc()
				.getInstance(AccountingSubjectManager.class);
		asList.clear();
		asList.addAll(asm.getSubjectListByCateId(this.sc.getCode()));
		Collections.sort(asList, sorter);
		super.fireTableDataChanged();
	}

	Comparator<AccountingSubject> sorter = new Comparator<AccountingSubject>() {

		@Override
		public int compare(AccountingSubject o1, AccountingSubject o2) {
			String key1 = String.valueOf(o1.getCode());
			String key2 = String.valueOf(o2.getCode());
			return key1.compareTo(key2);
		}
	};

	@Override
	public String getColumnName(int column) {
		return columnName[column];
	}

	public void showEditBtn(boolean selected) {
		this.showEditBtn = selected;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.AbstractTableModel#isCellEditable(int, int)
	 */
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return columnIndex == this.columnName.length - 1;
	}

}
